import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

// 使用相对路径导入组件（推荐）
const Home = () => import('../views/SKTStageWardrobeHome.vue')
const CostumeList = () => import('../views/Item/CostumeList.vue')
const CostumeDetail = () => import('../views/Item/CostumeDetail.vue')
const UserLogin = () => import('../views/User/userLogin.vue')
const UserInfo = () => import('../views/User/userInfo.vue')
const NotFound = () => import('../views/NotFound.vue')


const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
      meta: { title: '首页' }
    },
    {
      path: '/costumes',
      name: 'CostumeList',
      component: CostumeList,
      meta: { title: '服装列表' }
    },
    {
      path: '/costumes/:id',
      name: 'CostumeDetail',
      component: CostumeDetail,
      meta: { title: '服装详情' }
    },
    {
      path: '/login',
      name: 'Login',
      component: UserLogin,
      meta: { title: '登录', requiresGuest: true }
    },
    {
      path: '/register',
      name: 'Register',
      component: UserLogin,
      meta: { title: '注册', requiresGuest: true }
    },
    {
      path: '/user/info',
      name: 'UserInfo',
      component: UserInfo,
      meta: { title: '个人信息', requiresAuth: true }
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: NotFound,
      meta: { title: '页面未找到' }
    }
  ]
})

// 路由守卫保持不变
router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = `${to.meta.title} - SKT StageWardrobe`
  }

  const token = localStorage.getItem('token')
  const isLoggedIn = !!token

  if (to.meta.requiresAuth && !isLoggedIn) {
    ElMessage.warning('请先登录以访问此页面')
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
    return
  }

  if (to.meta.requiresGuest && isLoggedIn) {
    ElMessage.info('您已登录，正在跳转到首页')
    next('/')
    return
  }

  next()
})

export default router